package com.xyb.service;

import com.xyb.config.exception.MyException;
import com.xyb.dao.SysRoleDao;
import com.xyb.dao.SysUserDao;
import com.xyb.entity.*;
import com.xyb.utils.JwtUtils;
import com.xyb.vo.LoginVo;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class LoginService {
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysRoleDao sysRoleDao;

    /**
     * 根据手机号查询用户信息
     *
     * @param loginVo
     * @return
     */
    public UserInfo selectUserInfoByIphoneNo(LoginVo loginVo) {
        SysUser sysUser = sysUserDao.selectSysUserByIphoneNo(loginVo.getIphoneNo());    //根据手机号查询用户信息
        if (sysUser == null) {
            throw new MyException(StatusCode.PHONE_NO_NOT_REGISTERED_EXCEPTION);    //手机号未注册
        }
        String userPwd = sysUser.getUserPwd();  //数据库密码
        String pwd = loginVo.getPwd();          //前端传过来的密码
        boolean matches = passwordEncoder.matches(pwd, userPwd);
        if (!matches) {
            throw new MyException(StatusCode.USERNAME_OR_PASSWORD_ERROR_EXCEPTION);//账号或密码错误
        }
        if(sysUser.getStatus().intValue()==0){
            throw new MyException(StatusCode.ACCOUNT_LOCK_EXCEPTION);//账号已经冻结
        }
        //==================== 至此登录成功 ==============================================================================
        /**
         * 返回信息给前端
         * 1.token
         * 2.用户信息
         * 3.用户角色
         */
        Long userId = sysUser.getUserId();
        String userName = sysUser.getUserName();

        //根据用户id 查询用户角色
        List<SysRole> roleList = sysRoleDao.selectSysRoleListByUserId(userId);

        List<String> roles = new ArrayList<>();
        roleList.forEach(i -> {
            roles.add(i.getRoleName() + "," + i.getRoleId());
        });

        //生成 token
        JwtUtils.JwtUser jwtUser = JwtUtils.JwtUser.builder()
                .id(userId.toString())
                .subject(userName)
                .issuer("小猿邦")
                .audience(userName)
                .issuedAt(new Date())
                .expiration(null)
                .notBefore(null)
                .roleList(roles)
                .build();
        String token = JwtUtils.getToken(jwtUser);

        //封装 用户信息
        UserInfo userInfo = UserInfo.builder()
                .token(token)
                .userInfo(UserInfo.InnerUserInfo.builder()
                        .userId(userId)
                        .userName(userName)
                        .userNickName(sysUser.getUserNickName())
                        .iphoneNo(sysUser.getIphoneNo())
                        .headPortraitUrl(sysUser.getHeadPortraitUrl())
                        .status(sysUser.getStatus())
                        .roleList(roleList)
                        .build())
                .build();
        return userInfo;
    }
}




